<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2020/1/14
 * Time: 14:30
 */

namespace app\forum\home;

use app\common\controller\ApiBase;
use app\forum\model\PostComment;
use app\forum\model\PostLike;
use app\forum\model\PostReply;

class Reply extends ApiBase
{

    /**
     * 创建回复（ 回复留言或回复回复 ）
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function create()
    {
        // type = "comment|reply"
        $input = $this->getInput(["id", "type","content"]);

        $reply = new PostReply();
        $reply->from_uid = $this->getAuthorizeUID();
        $reply->content = $input["content"];
        $reply->comment_id = $input["id"];
        if($input["type"] == "reply"){
            $info = PostReply::get($input["id"]);
            $reply->top_id      = $info->id;
            $reply->comment_id  = $info->comment_id;
            $reply->to_uid      = $info->from_uid;
        }
        $reply->save();

        return $this->apiReturn(["data" => $reply]);
    }

    /**
     * 回复列表
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     * @throws \think\Exception\DbException
     */
    public function lists(){
        $input = $this->getInput(["id"]);

        // 回复列表
        $replys = function ($q) use($input){
            $user_id = $this->getAuthorizeUID();
            $q->with(["from_user","to_user"])
                ->withCount(["likes"])
                ->withAttr('is_like',function ($q,$data) use ($user_id){
                    return PostLike::isliked($data["id"]
                        ,$user_id,3);
                })
                ->lists($input)
                ->append(["is_like"]);
        };

        // 当前留言
        $data = PostComment::with(["user","replys"=>$replys])
            ->withCount(["replys","likes"])
            ->get($input["id"]);

        if(!$data) return $this->apiError(lang("content_not_found"));

        $data->is_like = PostLike::isliked($input['id']
            ,$this->getAuthorizeUID(),2);

        return $this->apiReturn(compact("data"));
    }

    /**
     * 点赞处理
     * @return \think\response\Json
     * @throws \app\common\exception\ApiError
     */
    public function likeHandle(){
        $this->getInput("id");
        $reply_id = $this->request->param("id");
        $user_id = $this->getAuthorizeUID();

        if(!PostReply::get($reply_id))
            return $this->apiError(lang("content_not_found"));

        $data = PostLike::handle(compact("user_id","reply_id"));

        return $this->apiReturn($data);
    }

}